package cn.zhxu.toys.captcha;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Troy.Zhou @ 2022/8/16 15:03
 */
public class CaptchaAttrs {

    private final Map<String, Object> map = new HashMap<>();

    public static CaptchaAttrs newAttrs() {
        return new CaptchaAttrs();
    }

    public CaptchaAttrs with(String key, Object value) {
        map.put(key, value);
        return this;
    }

    public <T> T require(String key, Class<T> type) {
        T value = get(key, type);
        if (value == null) {
            throw new IllegalStateException("No value for " + key);
        }
        return value;
    }

    public <T> T get(String key, Class<T> type, T defaultValue) {
        T value = get(key, type);
        if (value == null) {
            return defaultValue;
        }
        return value;
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key, Class<T> type) {
        Object value = map.get(key);
        if (type.isInstance(value)) {
            return (T) value;
        }
        return null;
    }

}
